import base64
import json

from django.http import JsonResponse, HttpResponse

from ad_manage.models import Advertisement
from adlist.controller import get_data_controller
from users.models import UserProfile
from django.shortcuts import render, redirect


def getData_api_auth(func):
    def inner(request, *args, **kwargs):
        auth_token = request.COOKIES.get('tooken')
        if auth_token == 'null' or auth_token is None:
            page = 1
            pageSize = 10
            advertisement = Advertisement.objects.all().exclude(logo='暂无').exclude(local_img='暂无').exclude(
                local_img='')
            token = request.COOKIES.get('tooken', '')
            public_time = request.GET.get('public_time')
            discover_time = request.GET.get('discover_time')
            search_text = request.GET.get('search_text')
            app_from = request.GET.get('app_from')
            advertisements = get_data_controller(page, pageSize, token, advertisement, public_time, discover_time,
                                                 search_text,
                                                 app_from)
            return JsonResponse(advertisements)
        else:
            payload = auth_token.split(".")[1] + "=="
            a = base64.b64decode(payload).decode('unicode_escape')
            user_info = json.loads(a)
            user_id = user_info.get("user_id")

            user = UserProfile.objects.filter(id=user_id)
            if user.count() > 0:
                return func(request, *args, **kwargs)
            else:
                return JsonResponse({'error': '账户不存在'})
    return inner

def request_validate(func):
    def inner(request, *args, **kwargs):
        auth_token = request.COOKIES.get('tooken')
        if auth_token == 'null' or auth_token is None:
            return render(request, 'html/main/error.html', None)
        else:
            payload = auth_token.split(".")[1] + "=="
            a = base64.b64decode(payload).decode('unicode_escape')
            user_info = json.loads(a)
            user_id = user_info.get("user_id")
            user = UserProfile.objects.filter(id=user_id)
            if user.count() > 0:
                return func(request, *args, **kwargs)
            else:
                return JsonResponse({'error': '账户不存在'})

    return inner


def request_auth(func):
    def inner(request, *args, **kwargs):
        auth_token = request.COOKIES.get('tooken')

        if auth_token is None or auth_token == 'null':
            return redirect('/')
        else:
            payload = auth_token.split(".")[1] + "=="
            a = base64.b64decode(payload).decode('unicode_escape')
            user_info = json.loads(a)
            user_id = user_info.get("user_id")

            user = UserProfile.objects.filter(id=user_id)
            if user.count() > 0:
                return func(request, *args, **kwargs)
            else:
                return redirect('/')
    return inner